//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.only4play.authcenter.infrastructure.security.providers.admin.handler;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.only4play.authcenter.infrastructure.security.providers.exception.BlackListException;
import com.only4play.authcenter.infrastructure.utils.HandleHttpErrorUtil;
import com.only4play.common.model.JsonObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    public CustomAuthenticationFailureHandler() {
    }

    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        try {
            if (e.getClass().isAssignableFrom(BlackListException.class)) {
                response.setStatus(HttpServletResponse.SC_OK);
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                JsonObject<String> jsonObject = JsonObject.fail("黑名单");
                ObjectMapper objectMapper = new ObjectMapper();
                response.getOutputStream().write(objectMapper.writeValueAsBytes(jsonObject));
            } else {
                HandleHttpErrorUtil.handleHttpError(request, response, e);
            }

        } catch (Exception ee) {
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "Unauthorized");
        }

    }
}
